package com.scvtc.utils;

import com.scvtc.domain.ForeignKeyCache;
import com.scvtc.domain.entity.student.StudentsBase;
import com.scvtc.domain.entity.teacher.TeacherBase;
import com.scvtc.domain.enums.OpType;
import com.scvtc.service.student.StudentsBaseService;
import com.scvtc.service.teacher.TeacherBaseService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

import static com.scvtc.constants.RedisConstant.STUDENT_BASE;
import static com.scvtc.constants.RedisConstant.TEACHER_BASE;

/**
 * @Description: 字典刷新工具类
 * @Author: yiFei
 * @date: 2022/5/27 18:09
 */
@Component
public class DictionaryUtil {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private StudentsBaseService studentsBaseService;

    @Autowired
    private TeacherBaseService teacherBaseService;

    private DictionaryUtil() {

    }

    public void refreshDictionary() {
        // 清除旧数据
        redisUtil.deleteObject(STUDENT_BASE);
        redisUtil.deleteObject(TEACHER_BASE);
        // 查询学生所有
        List<StudentsBase> students = studentsBaseService.list();
        // stream 流 封装出名字
        List<ForeignKeyCache> studentNameList = students.stream()
                .distinct()
                .map(item -> new ForeignKeyCache(item.getId(), item.getStuName(), item.getStuNum()))
                .collect(Collectors.toList());
        redisUtil.setCacheList(STUDENT_BASE, studentNameList);

        // 查询教师所有
        List<TeacherBase> teacher = teacherBaseService.list();
        // stream 流 封装出名字
        List<ForeignKeyCache> teacherNameList = teacher.stream()
                .distinct()
                .map(item -> new ForeignKeyCache(item.getId(), item.getTeacherName(), item.getTeacherCollegeId()))
                .collect(Collectors.toList());
        redisUtil.setCacheList(TEACHER_BASE, teacherNameList);
    }

    /**
     * 删除多条数
     */
    public void deleteMultiple(Long[] ids, String cacheKey, @NotNull OpType opType) {
        if (!OpType.DELETE_MULTIPLE.equals(opType)) {
            return;
        }

        List<ForeignKeyCache> data = getCacheData(cacheKey);
        //
        for (Long id : ids) {
            int cacheIndexById = getCacheIndexById(data, id);
            if (cacheIndexById != -1) {
                data.remove(cacheIndexById);
            }
        }
        /**
         * 删除原来的缓存数据 ， 添加新的
         */
        redisUtil.deleteObject(cacheKey);
        redisUtil.setCacheList(cacheKey, data);

    }


    /**
     * 更新学生信息
     *
     * @param object
     * @param cacheKey 缓存中的关键字
     * @param opType
     */
    public void refreshData(Object object, String cacheKey, @NotNull OpType opType) {
        List<ForeignKeyCache> data = getCacheData(cacheKey);
        Long id = -1L;
        int infoById;
        ForeignKeyCache foreignKeyCache = null;
        // 判断类型给  foreignKeyCache 赋值 （方便后续添加修改）
        if (STUDENT_BASE.equals(cacheKey)) {
            StudentsBase studentsBase = (StudentsBase) object;
            id = studentsBase.getId();
            foreignKeyCache = new ForeignKeyCache(studentsBase.getId(), studentsBase.getStuName(), studentsBase.getStuNum());
        }
        if (TEACHER_BASE.equals(cacheKey)) {
            TeacherBase teacherBase = (TeacherBase) object;
            id = teacherBase.getId();
            foreignKeyCache = new ForeignKeyCache(teacherBase.getId(), teacherBase.getTeacherName(), teacherBase.getTeacherCollegeId());
        }

        // 如果数据为空直接返回
        if (CollectionUtils.isEmpty(data) || ObjectUtils.isEmpty(foreignKeyCache)) {
            return;
        }

        // 判断操作类型进行处理
        switch (opType) {
            case SAVE:
                // 增加操作 (判断类型进行添加)
                data.add(foreignKeyCache);
                break;
            case UPDATE:
                // 修改操作
                infoById = getCacheIndexById(data, id);
                data.get(infoById).setId(foreignKeyCache.getId()).setValue(foreignKeyCache.getValue()).setJobNumber(foreignKeyCache.getJobNumber());
                break;
            case DELETE:
                // 删除操作
                infoById = getCacheIndexById(data, id);
                if (infoById != -1) {
                    data.remove(infoById);
                }
                break;
        }
        /**
         * 删除原来的缓存数据 ， 添加新的
         */
        redisUtil.deleteObject(cacheKey);
        redisUtil.setCacheList(cacheKey, data);
    }


    /**
     * 获取缓存信息 (只封装了一句 （尴尬）)
     *
     * @param cacheKey 缓存 key
     * @return
     */
    private List<ForeignKeyCache> getCacheData(String cacheKey) {
        return redisUtil.getCacheList(cacheKey);
    }


    /**
     * 定位缓存信息 (返回数据下标)
     *
     * @param data 数据
     * @param id   查询的下标
     * @return
     */
    private int getCacheIndexById(List<? extends ForeignKeyCache> data, @NotNull Long id) {
        // 获取数据对应下标
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getId().equals(id)) {
                return i;
            }
        }
        return -1;
    }


}
